<?php
/**
 * (jobs)
 */
namespace App\Jobs\ProductStockup;

use App\Models\Inventory\AreaCn;
use App\Models\Product\ProductSku;
use App\Models\ProductStockup\Stockup;
use App\Models\ProductStockup\StockupApplyLog;
use App\Models\Stocking\StockingApply;
use App\Models\Stocking\StockingSkuLog;
use App\Util\SerialNo;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class StockupOrderCreate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $stockups;

    /**
     * @param $stockups
     */
    public function __construct($stockups)
    {
        $this->stockups = $stockups;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->stockups);
    }

    private function exeFillData($stockups){
        foreach ($stockups as $stockup){

            if($stockup->confirm_num > 0){
                $item = [];
                $item['stocking_no'] = SerialNo::getBhNo();
                $item['area_id'] = $stockup->area_id;
                $item['psku_id'] = $stockup->psku_id;
                $item['seller_id'] = $stockup->apply_admin_id;
                $item['apply_num'] = $stockup->confirm_num; //供应链最终确认数量（实际备货数量）
                $ps = $this->_getProductById($stockup->psku_id);
                $itemDetail = [];
                $amount = 0;
                foreach ($ps as $k => $v){
                    $itemDetail[$k]['area_id'] = $stockup->area_id;
                    $itemDetail[$k]['psku_id'] = $v['psku_id'];
                    $itemDetail[$k]['apply_detail_num'] = $v['num'] * ($stockup->confirm_num);
                    $amount += $v['unit_price'] * $itemDetail[$k]['apply_detail_num'];
                }
                $item['amount'] = $amount;

                //备货单信息
                $stockingApply = StockingApply::query()->create($item);
                $stockingApply->detail()->createMany($itemDetail);
                $this->_addAreaCn($stockup->area_id,$stockup->psku_id);
            }
            StockingSkuLog::_addStockingSkuLog($stockup); //备货单日志

            //StockupApplyLog::_addStockupLog($stockup); //新备货日志
        }
    }

    private function _addAreaCn($areaId,$pSkuId){
        $count = AreaCn::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->count();
        if($count == 0){
            AreaCn::query()->create(['area_id' => $areaId,'psku_id' => $pSkuId]);
        }
    }

    private function _getProductById($pSkuId){
        return ProductSku::getMpSkuById($pSkuId);
    }

}
